package com.zzl.study.demo.tool;

import com.zzl.study.demo.domain.BaiduMapApiResponse;
import com.zzl.study.demo.domain.BaiduMapRegionLocation;
import com.zzl.study.demo.domain.Location;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.client.RestClient;

/**
 * 百度地图API服务
 *
 * @author: zhangzl
 * @date: 2025/10/10 15:17
 * @version: 1.0
 */
public class BaiduMapService {

    /**
     * 百度地图API基础URL
     */
    private static final String BAIDU_MAP_BASE_URL = "https://api.map.baidu.com/place/v3";

    /**
     * 百度地图API密钥
     */
    @Value("${baidu.map.api-key}")
    private String baiduMapApiKey;

    /**
     * 创建一个RestClient实例，用于发送HTTP请求百度地图
     */
    private final RestClient baiduMapRestClient;

    public BaiduMapService() {
        this.baiduMapRestClient = RestClient.builder()
                .baseUrl(BAIDU_MAP_BASE_URL)
                .build();
    }

    /**
     * 获取指定地点的经纬度详情
     *
     * @param locationName 地点名称
     * @return 地点的经纬度详情
     */
    @Tool(name = "get_latitude_and_longitude", description = "获取指定地点的经纬度详情")
    public String getLatitudeAndLongitude(@ToolParam(description = "地点名称") String locationName) {
        BaiduMapApiResponse response = this.baiduMapRestClient.get()
                .uri("/region?query={query}&region={region}&ak={ak}", locationName, locationName, this.baiduMapApiKey)
                .retrieve()
                .body(BaiduMapApiResponse.class);
        BaiduMapRegionLocation baiduMapRegionLocation = response.results().get(0);
        Location location = baiduMapRegionLocation.location();
        return String.format("""
                        %s的经纬度详情:
                        经度：%s,纬度：%s
                        """,
                baiduMapRegionLocation.name(),
                location.longitude(),
                location.latitude());
    }

}
